#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex;
int ticket = 100;
//自定义函数
void* Getticket(void* arg)
{
    const char* name = (char*)arg;
    while(1)
    {
        //加锁
        pthread_mutex_lock(&mutex);
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s finish get ticket : %d\n",name,ticket--);
            //解鎖
            pthread_mutex_unlock(&mutex);
        }else{
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    printf("%s quit\n",name);
    pthread_exit((void*)0);
}

int main()
{
    //初始化互斥量
    pthread_mutex_init(&mutex, NULL);
    //创建五个线程
    pthread_t p1,p2,p3,p4,p5;
    pthread_create(&p1, NULL, Getticket,"pthread-1");
    pthread_create(&p2, NULL, Getticket,"pthread-2");
    pthread_create(&p3, NULL, Getticket,"pthread-3");
    pthread_create(&p4, NULL, Getticket,"pthread-4");
    pthread_create(&p5, NULL, Getticket,"pthread-5");

    //线程等待
    pthread_join(p1,NULL);
    pthread_join(p2,NULL);
    pthread_join(p3,NULL);
    pthread_join(p4,NULL);
    pthread_join(p5,NULL);
    //释放互斥量
    pthread_mutex_destroy(&mutex);

    return 0;
}